package com.bieber.smartpost.invoke.filter;

import com.bieber.smartpost.httpcore.Response;
import com.bieber.smartpost.invoke.*;
import com.bieber.smartpost.model.RequestEntity;
import com.bieber.smartpost.util.Utils;
import com.jbeer.framework.annotation.Bean;
import com.jbeer.framework.utils.StringUtils;

/**
 * Created by bieber on 2014/11/12.
 */
@Bean
public class InvokerFilter extends AbstractFilter {

    public void doFilter(FilterChain chain, RequestEntity entity) {
        for(int i=0;i<entity.getInvokeTime();i++){
            HttpInvokerResult result = new HttpInvokerResult();
            result.setName(entity.getName());
            long start = System.currentTimeMillis();
            try {
                Response response =  HttpProxy.doRequest(entity, entity.getCookies());
                System.out.println("invoke "+entity.getUrl()+" response "+response.toString());
                if(!StringUtils.isEmpty(chain.getContext().getInvokeTask().getInvokeId())){
                    result.setHeader(response.getHeader().toString().replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll("\n","<br/>"));
                    result.setResponseContent(response.getResponseContent().replaceAll("<","&lt;").replaceAll(">","&gt;"));
                    result.setResponseCode(response.getResponseCode());
                    result.setContentType(response.getContentType());
                    result.setResponseHeader(response.getHeader());
                    result.setIndex(i + 1);
                    result.setEntityId(entity.getEntityId());
                    result.setExpendTime(System.currentTimeMillis() - start);
                    chain.getContext().getLastResponse().copyFrom(response);
                    CookieContainer.cacheCookies(chain.getContext().getInvokeTask().getInvokeId(), response.getHeader().getCookies());
                    BatchHttpInvokeResultQueue.putResult(chain.getContext().getInvokeTask().getInvokeId(),result);
                }
            } catch (Exception e) {
                Utils.COMMONS_LOGGER.debug("failed to invoke remote server", e);
                if(!StringUtils.isEmpty(chain.getContext().getInvokeTask().getInvokeId())){
                result.setIndex(i + 1);
                result.setResponseContent(Utils.formatExceptionContent(e));
                result.setResponseCode("500");
                result.setEntityId(entity.getEntityId());
                BatchHttpInvokeResultQueue.putResult(chain.getContext().getInvokeTask().getInvokeId(),result);
                }
            }
            try {
                Thread.sleep(entity.getIntervalTime());
            } catch (InterruptedException e) {
                Utils.COMMONS_LOGGER.debug("failed to invoke remote server", e);
            }
        }
        chain.doChain(entity);
    }



    public int order() {
        return Integer.MAX_VALUE;
    }
}
